<template>
  <view>
    <view class="movie-position">
      <view style="display: flex">
        <uni-icons
            type="left"
            size="24"
            @click="goBack"
            style="margin-right: 20rpx"
        ></uni-icons>
        <view class="position-text">{{ cinema.name }}</view>
      </view>
    </view>

    <!-- 轮播盒子 -->
    <view class="swiper_main">
      <image
          class="background-img-vague"
          style="width: 100vw"
          mode="widthFix"
          :src="chooseMovie.logo || ''"
      ></image>
      <view class="wrap">
        <Swipers
            :list="movieList"
            height="260"
            mode="none"
            name="logo"
            :autoplay="false"
            img-mode="scaleToFill"
            class="swiper_bg"
            :effect3d="true"
            bg-color="none"
            :circular="false"
            effect3d-previous-margin="280"
            @click="handleSwiperClick"
            @change="handleSwiperChange"
            :current="swiperCurrent"
        ></Swipers>
      </view>
      <div class="box"></div>
    </view>

    <!-- 电影信息 -->
    <view class="movie-info-section">
      <view class="movie-name">{{ chooseMovie.name || '加载中...' }}</view>
      <view class="movie-details">
        {{ chooseMovie.duration }}分钟 {{ chooseMovie.actors }}
      </view>
    </view>

    <!-- 日期标签 -->
    <view class="movie-tab-list" v-if="tabList.length > 0">
      <view
          class="tabs-list-item"
          :class="{ 'tab-sel': index === tabIndex }"
          v-for="(value, index) in tabList"
          :key="index"
          @click="handleDateTabClick(index)"
      >
        {{ value }}
        <view class="tab-indicator" v-if="index === tabIndex"></view>
      </view>
    </view>

    <!-- 场次列表 -->
    <view v-if="isLoading">
      <view class="loading-indicator">加载中...</view>
    </view>

    <view v-else-if="currentDateOpiList.length > 0">
      <view class="ticket-list" v-for="(value, index) in currentDateOpiList" :key="value.opiid">
        <view style="width: 79%">
          <view class="ticket-left">
            <view style="display: flex; align-items: center">
              <text class="left-time">{{ formatTime(value.playtime) }}</text>
              <text class="left-type">{{ value.edition }}</text>
            </view>
            <view style="display: flex; align-items: center">
              <view class="ret-price">
                <text>￥</text>
                {{ value.showPrice / 100 }}
              </view>
            </view>
          </view>
          <view class="ticket-left" style="margin-top: 20rpx">
            <view class="ticket-details">
              <text>时长:{{ calculateDuration(value.playtime, value.closetime) }}分钟</text>
              <text style="margin-left: 25rpx">{{ value.roomname }}</text>
            </view>
          </view>
        </view>
        <view class="buy-button" @click="handleBuyTicket(value)">购票</view>
      </view>
    </view>

    <view v-else class="no-schedule">
      暂无排片！
    </view>
  </view>
</template>

<script setup>
import {ref, computed, nextTick} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import Swipers from "./components/u-swiper.vue";
import {showAuthModal} from "@/sheep/hooks/useModal";
import sheep from "@/sheep";

// 响应式数据
const cinemaId = ref(null);
const filmName = ref(null);
const movieList = ref([]);
const cinema = ref({});
const chooseMovie = ref({
  id: '',
  name: '',
  logo: '',
  duration: '',
  actors: '',
  director: '',
  address: '',
  playdateList: [],
  opiList: []
});
const swiperCurrent = ref(0);
const movieIndex = ref(0);
const tabIndex = ref(0);
const tabList = ref([]);
const isLoading = ref(false);
const error = ref(null);
const isLogin = computed(() => sheep.$store("user").isLogin);

// 计算属性 - 当前日期的场次列表
const currentDateOpiList = computed(() => {
  if (!chooseMovie.value?.opiList || !chooseMovie.value?.playdateList || tabList.value.length === 0) {
    return [];
  }

  const selectedDate = chooseMovie.value.playdateList[tabIndex.value];
  return chooseMovie.value.opiList.filter(item => item.playdate === selectedDate);
});

// 生命周期钩子
onLoad((option) => {
  console.log('页面参数:', option);
  cinemaId.value = option.id;
  filmName.value = option.movieName;
  console.log('option: ', option);
  loadFilmList();
});

// 方法 - 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1
  });
};

// 方法 - 加载电影列表
const loadFilmList = async () => {
  try {
    isLoading.value = true;
    error.value = null;

    const res = await sheep.$api.xkMovie.getOpiList({
      cinemaId: cinemaId.value
    });

    if (res.code !== 200) {
      uni.showToast({
        title: res.message,
        icon: 'none'
      });
    }
    console.log('获取影院电影成功:', res.data);
    movieList.value = res.data.movieList || [];
    cinema.value = res.data.cinema || cinema.value;
    initializeMovieSelection();
  } catch (err) {
    console.error('加载电影列表错误:', err);
    error.value = err.message || '加载失败，请重试';
    uni.showToast({
      title: error.value,
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 方法 - 初始化电影选择
const initializeMovieSelection = () => {
  if (movieList.value.length > 0) {
    if (filmName.value) {
      // 查找指定电影
      const targetMovie = movieList.value.find(movie => movie.name === filmName.value);
      if (targetMovie) {
        chooseMovie.value = {...targetMovie};
        movieIndex.value = movieList.value.indexOf(targetMovie);
      } else {
        chooseMovie.value = {...movieList.value[0]};
      }
    } else {
      chooseMovie.value = {...movieList.value[0]};
    }
    // 修改这里：使用nextTick确保DOM更新后设置current
    nextTick(() => {
      swiperCurrent.value = movieIndex.value;
      console.log('初始化设置swiperCurrent:', movieIndex.value);
    });
    generateDateTabs();
  }
};

// 方法 - 生成日期标签
const generateDateTabs = () => {
  tabList.value = [];
  if (chooseMovie.value?.playdateList) {
    chooseMovie.value.playdateList.forEach(date => {
      tabList.value.push(formatDate(date));
    });
  }
  tabIndex.value = 0;
};

// 方法 - 轮播点击处理
const handleSwiperClick = (index) => {
  updateMovieSelection(index);
};

// 方法 - 轮播切换处理
const handleSwiperChange = (index) => {
  updateMovieSelection(index);
};

// 方法 - 更新选中的电影
const updateMovieSelection = (index) => {
  if (movieList.value && movieList.value[index]) {
    swiperCurrent.value = index;
    chooseMovie.value = {...movieList.value[index]};
    generateDateTabs();
    console.log('当前选中的电影:', chooseMovie.value);
  }
};

// 方法 - 日期标签点击处理
const handleDateTabClick = (index) => {
  tabIndex.value = index;
};

// 方法 - 购票按钮点击处理
const handleBuyTicket = (data) => {

  if (!isLogin.value) {
    // 用户未登录，弹出登录框
    handleLogin();
  }

  sheep.$router.go('/pages/xk-movie/seat', {
    movieItem: JSON.stringify(data),
    chooseMovie: JSON.stringify(chooseMovie.value),
  })
};

// 弹出登录框
function handleLogin() {
  if (sheep.$platform.name === "WechatMiniProgram") {
    showAuthModal("wechatMiniLogin");
  } else {
    showAuthModal("smsLogin");
  }
}

// 工具方法 - 日期格式化
const formatDate = (date) => {
  try {
    const time = new Date(date);
    return `${time.getMonth() + 1}-${time.getDate()}`;
  } catch (err) {
    console.error('日期格式化失败:', err);
    return date;
  }
};

// 工具方法 - 时间格式化
const formatTime = (timestamp) => {
  try {
    const date = new Date(timestamp);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  } catch (err) {
    console.error('时间格式化失败:', err);
    return timestamp;
  }
};

// 工具方法 - 计算电影时长
const calculateDuration = (startDate, endDate) => {
  try {
    const startTime = new Date(startDate);
    const endTime = new Date(endDate);
    const timeDiffMs = endTime - startTime;
    const minuteDiff = timeDiffMs / (1000 * 60);
    return Math.abs(Math.round(minuteDiff));
  } catch (err) {
    console.error('计算时长失败:', err);
    return 0;
  }
};
</script>

<style lang="scss" scoped>
// 轮播区域
.swiper_main {
  position: relative;
  height: 324rpx;
  overflow: hidden;

  .background-img-vague {
    position: absolute;
    left: 0;
    right: 0;
    width: 100%;
    filter: blur(15px);
    -webkit-filter: blur(15px);
  }

  ::v-deep .u-swiper-item {
    width: 193rpx !important;
    height: 260rpx !important;
  }

  .wrap {
    position: absolute;
    left: 0;
    top: 26rpx;
    right: 0;
    margin: 0 auto;
  }

  .box {
    width: 0;
    height: 0;
    border: 10rpx solid;
    border-color: transparent transparent #fff #fff;
    transform: rotate(135deg);
    position: absolute;
    bottom: -10rpx;
    left: 0;
    right: 0;
    margin: 0 auto;
  }
}

// 影院位置信息
.movie-position {
  padding: 30rpx 32rpx;
  margin-top: 100rpx;

  .position-text {
    color: #2d3039;
    font-size: 32rpx;
    font-weight: 550;
  }
}

// 电影信息区域
.movie-info-section {
  .movie-name {
    text-align: center;
    margin-top: 30rpx;
    color: #2d3039;
    font-size: 36rpx;
    font-weight: 600;
  }

  .movie-details {
    text-align: center;
    margin-top: 14rpx;
    color: #636775;
    font-size: 24rpx;
  }
}

// 日期标签列表
.movie-tab-list {
  margin-top: 40rpx;
  padding: 24rpx 12rpx;
  border-bottom: 2rpx solid #dfe0e2;
  overflow-x: auto;
  white-space: nowrap;
  width: auto;
  overflow-y: hidden;

  .tabs-list-item {
    padding: 0rpx 20rpx;
    display: inline-block;
    position: relative;
    color: #636775;
    font-size: 28rpx;
    transition: color 0.3s ease;

    &.tab-sel {
      color: #fe602b !important;
      font-weight: 550;
    }

    .tab-indicator {
      position: absolute;
      bottom: -30rpx;
      right: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 52rpx;
      height: 8rpx;
      background-color: #fe602b;
    }
  }
}

// 加载指示器
.loading-indicator {
  text-align: center;
  padding: 60rpx 0;
  color: #636775;
  font-size: 28rpx;
}

// 无排片提示
.no-schedule {
  text-align: center;
  padding: 60rpx 0;
  color: #a6a8ae;
  font-size: 28rpx;
}

// 场次列表
.ticket-list {
  margin: 0rpx 32rpx;
  padding: 38rpx 0rpx;
  border-bottom: 2rpx solid #e0e1e3;
  display: flex;
  align-items: center;
  transition: background-color 0.2s ease;

  &:active {
    background-color: #f8f8f8;
  }

  .ticket-left {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left-time {
      color: #2d3039;
      font-size: 42rpx;
    }

    .left-type {
      color: #2d3039;
      font-size: 28rpx;
      margin-left: 32rpx;
    }
  }

  .ret-price {
    color: #fe602b;
    font-size: 42rpx;
    font-weight: 550;

    text {
      font-size: 28rpx;
    }
  }

  .ticket-details {
    color: #a6a8ae;
    font-size: 24rpx;
  }

  .buy-button {
    width: 110rpx;
    height: 58rpx;
    text-align: center;
    line-height: 58rpx;
    background: linear-gradient(207deg, #ff9272 0%, #fc5421 100%);
    border-radius: 30rpx;
    color: #ffffff;
    font-size: 24rpx;
    font-weight: 550;
    margin-left: auto;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.95);
    }
  }
}
</style>
